package com.rq.base.util;

import android.util.Log;

import android.text.TextUtils;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

public class GsonUtil {

  public static <T> T getBean(String json, Class<T> clazz) {
    try {
      return new Gson().fromJson(json, clazz);
    } catch (Exception e) {
      Log.e("GsonUtil", "getBean.21:" + e.getMessage());
      e.printStackTrace();
      return null;
    }
  }

  //  Type type = new TypeToken<List<Remark>>() {}.getType();
  //  ArrayList<Remark> list = GsonUtil.getList(Value, type);
  public static <T> T getList(String json, Type clazz) {
    try {
      return (T) new Gson().fromJson(json, clazz);
    } catch (Exception e) {
      e.printStackTrace();
      return null;
    }
  }

  public static String getString(Object object) {
    if (object == null) return "null";
    return new Gson().toJson(object);
  }

//    @Deprecated
//    public static <T> List<T> getList(String json,Class lcass) {
//
//        try {
//            return new Gson().fromJson(json, new TypeToken<List<T>>() {
//            }.getType());
//        } catch (JsonSyntaxException e) {
//            e.printStackTrace();
//            return null;
//        }
//    }


  public static <T> List<T> getMapList(String json, Class<T> cls) {
    List<T> list = new ArrayList<T>();
    try {
      Gson gson = new Gson();
      JsonArray arry = new JsonParser().parse(json).getAsJsonArray();
      for (JsonElement jsonElement : arry) {
        list.add(gson.fromJson(jsonElement, cls));
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    return list;
  }


  public static String toJson(Object obj) {
    try {
      if (obj instanceof String) {
        return (String) obj;
      }
      return new Gson().toJson(obj);
    } catch (Exception e) {
      e.printStackTrace();
      return null;
    }
  }

}
